package com.example.player.presentation.fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.player.R;
import com.example.player.dao.AppDatabase;
import com.example.player.dao.viewmodel.SharedViewModel;
import com.example.player.dao.viewmodel.SongViewModel;
import com.example.player.presentation.adaptor.SongItemAdapter;
import com.example.player.domain.entity.Song;
import com.example.player.util.MusicUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

/**
 * 本地音乐，对应local_music.xml
 *
 * @author 朱文权
 */
public class LocalMusicFragment extends Fragment {
    /**
     * 共享数据
     * */
    private SharedViewModel shared;
    /**
     * 统一管理订阅
     */
    private CompositeDisposable disposables = new CompositeDisposable();
    private SongViewModel model;
    /**
     * 现有的音乐
     * */
    private List<Song> songList = new ArrayList<>();
    /**
     * 歌曲条目适配器
     */
    private SongItemAdapter adapter;
    /**
     * 歌曲单项展示条目
     */
    private RecyclerView recyclerView;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.local_music, container, false);
        //绑定recycleView页面
        recyclerView = view.findViewById(R.id.recycle_view);
        recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 1));
        // 添加分割线
        recyclerView.addItemDecoration(
                new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL)
        );
        //将歌曲条目绑定至页面
        adapter = new SongItemAdapter(songList);
        recyclerView.setAdapter(adapter);
        //初始化viewmodel
        model = new SongViewModel(AppDatabase.getInstance(view.getContext()).songDao());
        //点击按钮添加歌曲
        view.findViewById(R.id.btn_add).setOnClickListener(btnAdd -> {
            //异步添加歌曲
            Set<Song> storeSongs=Set.copyOf(songList);
            disposables.add(
                    Observable.fromCallable(()->{
                        return MusicUtil.getNewSongs(getContext(),storeSongs);
                    })
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(newSongs->{
                                disposables.add(model.insert(newSongs));
                            })
            );
        });
        //点击按钮清除歌曲
        view.findViewById(R.id.btn_clear).setOnClickListener(btnClear -> {
            disposables.add(model.deleteAll());
        });
        //初始化共享viewmodel
        shared=new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
        //监听数据变化,及时更新数据
        shared.getLocalMusicSongs().observe(getViewLifecycleOwner(),songList->LocalMusicFragment.this.songList=songList);

        //异步查询数据,更新共享数据,并将其渲染至页面，该渲染实时检测数据库更新
        disposables.add(model.getAllSongs()
                .subscribe(data->{
                    //渲染数据
                    adapter.setData(data);
                    //共享数据
                    shared.setLocalMusicSongs(data);
                        },
                        error -> Log.e("ERROR", "查询数据失败" + error))
        );
        getMessage();
        return view;
    }

    /**
     * 接受其他组件发送的数据
     */
    private void getMessage() {
        //设置接受什么身份性质的信息
        String token = "TopNavigatorFragment";
        //所取信息的键
        String key="sendSongs";
        //接受音乐查找发送来的数据并进行渲染
        getParentFragmentManager().setFragmentResultListener(token, this, (requestKey, result) -> {
            List<Song> songs = (List<Song>) result.get(key);
            if (songs != null) {
                //渲染数据
                adapter.setData(songs);
                Log.d("TAG","成功渲染数据");
            } else {
                Log.w("WARNING","发送的数据为空");
            }
        });
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        //释放异步订阅
        disposables.clear();
        //释放适配器资源
        adapter.release();
    }
}
